﻿@model StackExchange.DataExplorer.Models.Site
@using StackExchange.DataExplorer
@using StackExchange.DataExplorer.Helpers
@using StackExchange.DataExplorer.Models
@{this.SetPageTitle("Query " + Model.LongName + " - Stack Exchange Data Explorer");}

@section AdditionalStyles{
    @Html.Raw(AssetPackager.LinkCss("query"))
    <style type="text/css">
        @Html.Raw(Model.TagCss)
    </style>
}

@{
    string sql;
    var query = ViewData["query"] as Query;
    if (query != null)
    {
        sql = query.QueryBody;
    }
    else
    {
        sql = ParsedQuery.DefaultComment;
    }

    sql = Html.Encode(sql);

    var cached_results = ViewData["cached_results"] as CachedResult;
    var description = (query != null && query.Description != null) ? query.Description : ParsedQuery.DEFAULT_DESCRIPTION;
}

<div id="queryText">
    <div id="queryInfo">
        <h2>@((query != null && query.Name != null) ? query.Name : ParsedQuery.DEFAULT_NAME)</h2>
        <p>@Html.Raw(description == null ? "" : Html.Encode(description).Replace("\n", "<br />"))</p>
    </div>
    @Html.Partial("AboutSite", Model)
    <div class="clear"></div>
    <div class="query" style="width:70%;">
        <form id="runQueryForm" action="/query/@Model.Id" method="post">
            <div id="sqlQueryWrapper" style="position:relative;">
                <textarea id="sqlQuery" name="sql" rows="18">@Html.Raw(sql)</textarea>
            </div>
            <div class="clear"></div>
            <a id="schemaToggle" href="#">hide schema &gt;&gt;</a>
            <div id="queryParams" style="display:none;">
                <h3>Enter Parameters</h3>
            </div>
            <ul id="query-options">
                <li>
                    <input type="hidden" name="siteId" value="@Model.Id" />
                    <label><input type="checkbox" name="resultsToText" value="true" />Results to text</label>
                </li>
                <li>
                    <label><input type="checkbox" name="showExecutionPlan" value="true" />Include execution plan</label>
                </li>
            @if (AppSettings.AllowRunOnAllDbsOption)
            {
                <li>
                    <label><input type="checkbox" name="allDbs" value="true" />Run as a mutli-site query</label>
                </li>
                <li>
                    <label><input type="checkbox" name="excludeMetas" value="true" />Exclude meta sites</label>
                </li>
            }
            </ul>

            @if (Current.User.IsAnonymous)
            {
                @Html.Partial("Captcha", Current.NewRecaptchControl())
            }
                
            <div id="toolbar">
                <input type="submit" value="Run Query" />

                <span id="permalinks" style="display:none;">
                    <a id="permalink" href="#">permalink to this query</a>
                    <a id="saveQuery" href="#">save query</a>
                    <a id="downloadCsv" href="#" title="download results as CSV">download results</a>
                    <a id="downloadPlan" href="#" title="download execution plan as XML">download execution plan</a>
                    @foreach (Site site in (IEnumerable<Site>)ViewData["Sites"])
                    {
                        if (site.Id == Model.Id) { continue; }
                        <a class="otherPermalink" href="/@site.Name.ToLower()/q//" title="View results on @site.LongName">
                            <img src="@site.IconUrl" alt="@site.LongName" width="16" height="16" />
                        </a>
                    }
                </span>
            </div>
        </form>
        <div class="clear"></div>        
        <div id="saveDialog" style="position:relative; display:none;">
            <form id="saveQueryForm" action="#" method="post">
                <input type="hidden" name="savedQueryId" class="savedQueryId" value="@ViewData["SavedQueryId"]" />
                <div class="overlay">&nbsp;</div>
                <div class="dialog">
                    <label>Title</label>
                    <input type="text" name="title" value="" class="title" />
                    <textarea name="description" class="description" cols="80" rows="5"></textarea>
                    <div class="savePanel">
                        <input type="submit" class="save" name="saveButton" value="Save" />
                        <input type="button" class="cancel" name="cancelButton" value="Cancel" />
                    </div>
                    <p class="error ui-state-error" style="display:none;"></p>
                </div>
            </form>
        </div>

        <div style="padding:5px; display:none;" class="ui-state-error ui-corner-all" id="query-errors">
            <p>
                <span style="float:left; margin-right:0.3em;" class="ui-icon ui-icon-alert"></span>
                <strong>Error:</strong> <span id="queryError"> </span>
            </p>
        </div>
        <div class="clear"></div>
    </div>
    <ul class="schema">
        @foreach (TableInfo table in (IEnumerable<TableInfo>)ViewData["Tables"])
        {
            <li>
                <span class="schema-table">@table.Name</span>
                <dl>
                    @for (int i = 0; i < table.ColumnNames.Count; i++)
                    {
                        <dt>@table.ColumnNames[i]</dt>
                        <dd class="cm-variable-2">@table.DataTypes[i]</dd>
                    }
                </dl>
            </li>
        }
    </ul>
</div>
        
<div class="clear"></div>

<p style="display:none;" class="loading">
    <img src="http://sstatic.net/img/progress-dots.gif" />
    <span>Hold tight while we fetch your results</span>
</p>

@Html.Partial("~/Views/Shared/QueryResults.cshtml")

@Html.Raw(AssetPackager.ScriptSrc("jquery.validate"))
@Html.Raw(AssetPackager.ScriptSrc("query"))

<script type="text/javascript">
    var siteId = @Model.Id;
    var loggedOn = @((!Current.User.IsAnonymous).ToString().ToLower());

    @Html.Partial("GuessedUserId")

    var codemirror; 

    function getQueryInfo(text) {
        var info = {title: "", description: ""};
        var lines = text.split("\n"); 
        var gotTitle = false; 
      
        for (var i = 0; i < lines.length; i++) {
        if (lines[i].match("^--") == "--") {
            var data = lines[i].substring(2).replace(/^\s+|\s+$/g,"");
            if (gotTitle) {
            info.description += data + "\n";
            } else {
            info.title = data;
            gotTitle = true;
            }
        } else {
            break;
        }
        }
        return info;
    }
</script>